﻿using System.Collections.Generic;

namespace xshare
{


    public static class ListExt
    {

        public static int ResetAll<T>(this List<T> list, T item) where T : class
        {
            var count = 0;
            for (var i = 0; i < list.Count; ++i)
            {
                var temp = list[i];
                if (temp == item)
                {
                    list[i] = null;
                    count++;
                }
            }

            return count;
        }

        public static bool ResetOne<T>(this List<T> list, T item) where T : class
        {
            for (var i = 0; i < list.Count; ++i)
            {
                var temp = list[i];
                if (temp == item)
                {
                    list[i] = null;
                    return true;
                }
            }

            return false;
        }

        public static void ClearNull<T>(this List<T> list)
        {
            var ct = list.Count;
            if (ct < 5) //数量比较少
                return;

            //===== 检查null元素数量
            var nullCt = 0;
            var firstNullIndex = -1;
            for (var i = 0; i < ct; ++i)
            {
                if (null == list[i])
                {
                    if (-1 == firstNullIndex)
                        firstNullIndex = i;
                    nullCt++;
                }

                if (nullCt > 5)
                    break;
            }
            if (nullCt <= 5)
                return;
            //=====

            //===== 非null元素前移
            int j = firstNullIndex;
            for (var i = firstNullIndex + 1; i < ct; ++i)
            {
                if (null != list[i])
                    list[j++] = list[i];
            }
            //=====

            list.RemoveRange(j, ct - j);
        }

    } //end of class


}
